package com.hb.medical_research_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.medical_research_system.common.Results;
import com.hb.medical_research_system.common.UserThreadLocal;
import com.hb.medical_research_system.entity.User;
import com.hb.medical_research_system.service.UserService;
import com.hb.medical_research_system.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

/**
* @author hb
* @description 针对表【user(员工信息)】的数据库操作Service实现
* @createDate 2023-02-27 19:38:27
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    /**
     * 修改用户密码
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @Override
    public Results modifyPassword(String oldPwd, String newPwd) {
        log.info("进入修改密码流程");

        //密码为空,错误
        if(StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd)){
            return Results.info(Results.ERROR,"密码不得为空");
        }

        //获取当前登录id
        Long userId = UserThreadLocal.get().getUserId();

        //获取现密码
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.select("username", "password","flag").eq("user_id", userId);
        User user = userMapper.selectOne(userQueryWrapper);

        String realpassword = user.getPassword();


        //将旧密码md5处理
        oldPwd = DigestUtils.md5DigestAsHex(oldPwd.getBytes());

        //若密码错误,修改失败
        if(!oldPwd.equals(realpassword)){
            return Results.info(Results.ERROR,"原密码错误,请输入正确的密码");
        }else {

            //密码MD5处理
            String newpassword = DigestUtils.md5DigestAsHex(newPwd.getBytes());

            //修改密码
            LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.set(User::getPassword, newpassword ).eq(User::getUserId, userId);
            userService.update(lambdaUpdateWrapper);

            log.info("密码修改成功");
        }
        return Results.info(Results.SUCCESS,"密码修改成功");
    }
}




